package com.frp.lib.message;

import com.frp.lib.utils.JSON;

import java.io.*;

/**
 * Created by hujianjun on 11/22 0022.
 */
public class PackMsg {
    public static byte[] pack(Message msg) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(bos);
        Byte type = Message.TypeStringMap.get(msg.getClass());
        if (null==type) {
            throw new RuntimeException("message type error!");
        }
        try {
            byte[] content = JSON.toJsonBytes(msg);
            if (null==content) {
                throw new RuntimeException("to json error.");
            }
            dos.writeByte(type.byteValue());
            dos.writeLong(content.length);
            dos.write(content);
        } catch (IOException e) {
            throw new RuntimeException("pack error", e);
        }
        return bos.toByteArray();

    }

    public static Message unpack(byte[] data) {
        ByteArrayInputStream bis = new ByteArrayInputStream(data);
        DataInputStream dis = new DataInputStream(bis);
        try {
            byte type = dis.readByte();
            int length = (int) dis.readLong();
            byte[] content = new byte[length];
            int len = dis.read(content);
            Class<? extends Message> clazz = Message.TypeMap.get(type);
            if (null == clazz) {
                throw new RuntimeException("can not find message define for type:" + type);
            }
            Message msg = JSON.fromJsonBytes(content, clazz);
            return msg;
        } catch (IOException e) {
            throw new RuntimeException("unpack error io.", e);
        }
    }
}
